package bw.tools;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import bw.os.*;
import bw.util.*;

public class RemoteStoreMigrator extends HttpServlet
{
    public void doGet ( HttpServletRequest req, HttpServletResponse res )
        throws ServletException, IOException
    {
        if ( !"true".equals( req.getParameter( "doMigrate" ) ) )
        {
            return;
        }

        res.setContentType( "text/plain" );
        PrintWriter out = res.getWriter();

        try
        {
            GoogleDatastoreHandler source = new GoogleDatastoreHandler( null );
        
            String root = getServletContext().getInitParameter( "objectStore.httpWriter.root" );
            HttpObjectWriter writer = new HttpObjectWriter( root );

            out.println( "Getting objects from data store ..." );
            Hashtable objects = source.readAll();

            out.println( "Writing objects to remote store ..." );
            Iterator keys = objects.keySet().iterator();
            while ( keys.hasNext() )
            {
                String key = (String) keys.next();
                Object obj = objects.get( key );
                
                out.println( "Writing object: " + key );
                writer.lowlevelWrite( key, obj );
            }
        }
        catch ( Exception ex )
        {
            Log.getInstance().write( "Problem migrating to Remote Store!", ex );
        }

        out.println( "Done!" );
        out.close();
    }
}